import storage from "../global/storage";
import { ElLoading } from 'element-plus';
import NProgress from 'nprogress'; // 加载条
import 'nprogress/nprogress.css';

export default {
    /**
     * 路由鉴权
     * @param {*} router 全局路由实例
     */
    redirectRoutes(router) {
        const token = storage.get('token');

        router.beforeEach((to, from, next) => {
            /* 未登录 */
            if (!token && to.name != "Login") return next({ name: "Login", replace: true });
            /* 已登录 */
            if (token && to.name === "Login") return next({ name: "Home", replace: true });
            if (token && to.name === "Root") return next({ name: "Home", replace: true });

            next();
        });
    },

    /**
     * 加载条及loading
     * @param {*} router 全局路由实例
     */
    nprogress(router) {
        let loadingInstance = '';

        router.beforeEach((to, from, next) => {
            if (to.name === 'Login' || to.name === 'Root') return next();

            // 每次点击前看是否存在未关闭等待条，有就关掉，重新创建
            loadingInstance && loadingInstance.close();

            loadingInstance = ElLoading.service({
                lock: true,
                background: '#fff',
                target: document.querySelector('#app-router')
            });

            // 开启加载条
            NProgress.start();

            next();
        });

        router.afterEach((to) => {

            if (to.name === 'Login' || to.name === 'Root') return;

            // 延迟500毫秒关闭等待条
            setTimeout(() => {
                loadingInstance.close();
            }, 500);

            // 关闭加载条
            NProgress.done();
        });
    }
};